import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../Layout/Home.vue'

import local from '../utils/local.js'
import SyncRoutes from './syncRouter.js'

// 解决ElementUI导航栏中的vue-router在3.0版本以上重复点菜单报错问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

Vue.use(VueRouter)
const routes = [
  {
    path: '/',
    name: 'Home',
    // 重定向
    redirect: '/dashboard',
    component: Home,
    children: [
      {
        path: '/dashboard',
        meta: { name: '首台首页' },
        component: () =>
          import(/* webpackChunkName: "login" */ '../views/Dashboard/index.vue')
      }
    ]
  },
  {
    path: '/login',
    component: () => import('../views/Login/index.vue')
  },
  {
    path: '*',
    redirect: '/404'
  },
  {
    path: '/404',
    component: () => import('../views/404/index.vue')
  }
]

const router = new VueRouter({
  routes
})

// 根据不同的登录角色来确定要展示的路由信息
getSyncRouter()
export function getSyncRouter() {
  const role = local.get('role')
  if (!role) return
  console.log(role)
  // 获取最终能展示的路由数组 ? 凭借的是登录者的role
  const fillnaRoute = calcRoute(SyncRoutes.routes, role)
  console.log(fillnaRoute)
  // 最终合并到主路由
  routes[0].children = fillnaRoute

  console.log(router, routes[0])
  router.addRoutes([routes[0]])

  // 设计一个函数用于过滤掉菜单中不需要展示的页面
  const menuArr = calcMenu(fillnaRoute)
  local.set('menu', JSON.stringify(menuArr))
}
// 计算菜单项的
function calcMenu(arr) {
  console.log(arr, 22)
  return arr.filter(item => {
    if (!item.hidden) {
      // 由于还有二级路由, 还需要再递归
      if (item.children) {
        console.log(item.children, 1)
        item.children = calcMenu(item.children)
      }
      return true
    } else {
      return false
    }
  })
}
// 过滤路由数组
function calcRoute(arr, role) {
  return arr.filter(item => {
    if (hasPermission(item, role)) {
      if (item.children) {
        item.children = calcRoute(item.children, role)
      }
      return true
    } else {
      return false
    }
  })
}
// 声明一个鉴权的函数
function hasPermission(obj, role) {
  if (obj.meta && obj.meta.role) {
    return obj.meta.role.includes(role)
  } else {
    return true
  }
}

// 使用导航守卫对页面进行拦截
router.beforeEach((to, from, next) => {
  const token = local.get('token')
  if (token) {
    next()
  } else {
    if (to.path === '/login') {
      next()
    } else {
      next('/login')
    }
  }
})

export default router
